package com.snail.common.core.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.snail.common.core.utils.sql.SqlUtil;
import com.snail.common.core.web.domain.BaseQuery;
import com.snail.common.core.web.page.PageDomain;
import com.snail.common.core.web.page.PageResult;
import com.snail.common.core.web.page.TableSupport;

/**
 * 分页工具类
 *
 * @author snail
 */
public class PageUtils extends PageHelper {
    /**
     * 设置请求分页数据
     */
    public static void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        Boolean reasonable = pageDomain.getReasonable();
        PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
    }

    /**
     * 清理分页的线程变量
     */
    public static void clearPage() {
        PageHelper.clearPage();
    }

    /**
     * 封装分页查询参数
     */
    public static <T> Page<T> buildPage(BaseQuery query) {
        Page<T> page = new Page<>(1, 10);
        if (query != null) {
            page.setSize(query.getPageSize());
            page.setCurrent(query.getPageNum());
        }
        if(StringUtils.isNotEmpty(query.getOrderByColumn())){
            orderBy(query);
        }
        return page;
    }

    /**
     * 封装分页返回参数
     */
    public static <T> PageResult<T> pageResult(IPage<T> page) {
        PageResult<T> pageResult = new PageResult<>();
        pageResult.setPageNum(page.getCurrent());
        pageResult.setPageSize(page.getSize());
        pageResult.setTotal(page.getTotal());
        pageResult.setRows(page.getRecords());
        return pageResult;
    }

    public static void orderBy(BaseQuery query) {
        orderBy(query.getOrderByColumn() + " " + query.getOrderByType());
    }
}
